/*
 * MapObject.cpp
 *
 *  Created on: 25 Oct 2013
 *      Author: Patrick
 */

#include <vector>
#include <iostream>

#include <OgreManualObject.h>
#include <OgreSceneManager.h>
#include <OgreColourValue.h>

#include "MapObject.h"

namespace Engine {

MapObject::MapObject(std::vector<Ogre::Vector3> pointList, bool closed) {
	this->renderObject = NULL;
	this->points = pointList;

	if(closed)
		this->points.push_back(this->points[0]);
}

MapObject::~MapObject() {
}

Ogre::ManualObject* MapObject::getRenderObject(Ogre::SceneManager* sceneMgr, Ogre::ColourValue colour) {
	if(this->renderObject == NULL)
		this->drawRenderObject(sceneMgr, colour);

	return this->renderObject;
}

void MapObject::drawRenderObject(Ogre::SceneManager* sceneMgr, Ogre::ColourValue colour) {
	Ogre::ManualObject* heightLines = sceneMgr->createManualObject();

//	this->tangents.resize(this->points.size());
//	for(unsigned int i = 0; i < this->points.size(); i++) {
//		tangents[i] = ((this->getPoint(i+1) - this->getPoint(i-1)) * 0.5);
//		tangents[i].normalise();
//	}

	/*
	 * lines
	 */
	heightLines->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_LINE_STRIP);

//	for(unsigned int i = 0; i <= this->points.size(); i++) {
//
//		Ogre::Vector3 p0 = this->getPoint(i);
//		Ogre::Vector3 p1 = this->getPoint(i+1);
//		Ogre::Vector3 t0 = this->getTangent(i);
//		Ogre::Vector3 t1 = this->getTangent(i+1);
//
//		float length = (p1 - p0).length();
//		float step = 0.1 * length;
//
//		for(float t = 0.0f; t < length; t += step) {
//
//			Ogre::Vector3 p = (2.0*t*t*t - 3.0*t*t + 1.0) * p0
//					+ (t*t*t - 2.0*t*t + t) * t0
//					+ (-2.0*t*t*t + 3.0*t*t) * p1
//					+ (t*t*t - t*t) * t1;
//
//			heightLines->position(p);
//			heightLines->colour(colour);
//		}
//	}



	for(unsigned int i = 0; i < this->points.size(); i++) {
		heightLines->position(this->points[i]);
		heightLines->colour(colour);
	}

	heightLines->end();
	//end of lines

	this->renderObject = heightLines;
}

Ogre::Vector3 MapObject::getPoint(int i) {
	int a = i;

	if(a >= this->points.size())
		a %= this->points.size();

	return this->points[a];
}

Ogre::Vector3 MapObject::getTangent(int i) {
	int a = i;

	if(a >= this->points.size())
		a %= this->points.size();

	return this->tangents[a];
}

} /* namespace Engine */
